import { getAllMenu } from '@/apis/accessManagement/menu'
import { getSingleMenuInfo } from '@/apis/accessManagement/menu'
import { addMenu } from '@/apis/accessManagement/menu'
import { editMenu } from '@/apis/accessManagement/menu'
import { useRef,useState,useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import layout from './index.module.scss'
import { Button, Tabs, Form, Input, Select, Switch,Flex,message,Spin,TreeSelect,Radio } from 'antd'
import { useLocation } from 'react-router-dom'
import type { RadioChangeEvent } from 'antd';

const menuDetail = () => {
    const {TextArea} = Input
    const [form] = Form.useForm()
    const navigate = useNavigate()
    const location = useLocation()
    const query = new URLSearchParams(location.search)
    const state = query.get('state')
    const menuId = query.get('menuId')
    const [showPwd, setShowPwd] = useState(false)
    const [loading, setLoading] = useState(false)
    const [messageApi, contextHolder] = message.useMessage()
    const [value, setValue] = useState(undefined)
    const [radioValue, setRadioValue] = useState(1)
    const [treeData, setTreeData] = useState([])
    const [parentStatus, setParentStatus] = useState(0)
    const [defaultMenuName, setDefaultMenuName] = useState('')
    const [defaultMenuType, setDefaultMenuType] = useState(0)
    const [defaultParentId, setDefaultParentId] = useState(0)
    const [defaultPath, setDefaultPath] = useState('')
    // const [defaultParentObj, setDefaultParentObj] = useState({})
    const [defaultSort, setDefaultSort] = useState('')
    const [defaultStatus, setDefaultStatus] = useState(0)
    const [defaultCache, setDefaultCache] = useState(0)
    const [defaultIcon, setDefaultIcon] = useState('')

    const onRadioChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value)
        setValue(e.target.value)
    }

    const onTreeChange = (newValue: any,label:any,extra:any) => {
        // console.log(newValue) setDefaultParentId
        const selectedNode = extra.triggerNode;
        // console.log("Selected Node Data:", !!selectedNode?.props?.menuParentId)
        if(!newValue){
            setParentStatus(0)
            setDefaultParentId(0)
        }else{
            setParentStatus(selectedNode.props.menuId)
            setDefaultParentId(selectedNode.props.menuId)
        }
        setValue(newValue);
    }

    // 查询单个菜单信息
    const getMenuInfo = async () => {
        setLoading(true)
        try {
            const response = await getSingleMenuInfo({
                menuId:parseInt(menuId),
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    const menuName = response.data.menuName
                    const menuType = response.data.menuType
                    const sort = response.data.sort
                    const path = response.data.path
                    const status = response.data.status
                    const cache = response.data.cache
                    setDefaultMenuName(menuName || '暂无数据')
                    setDefaultMenuType(menuType)
                    setDefaultSort(sort)
                    setDefaultParentId(response.data.menuParentId?response.data.menuParentId:null)
                    setDefaultPath(path)
                    setDefaultStatus(status)
                    setDefaultCache(cache)
                    setDefaultIcon(response.data.icon?response.data.icon:'')
                    setParentStatus(response.data.menuParentId?response.data.menuParentId:0)
     
                    // console.log(treeData)
                } else {
                    message.error(`查询失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 查询所有菜单
    const getAllMenuInfo = async ()=> {
        setLoading(true)
        try {
            const response = await getAllMenu({
                pagination: {pageNumber:1,showNumber:100}, 
                menuName:'',
                roleCode:'',
                status:null,
                menuType:0,
                path:'',
                updateBy:'',
                startTime:'',
                endTime:'',
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    const menuMap = new Map();
                    const tree = [];
                    // 初始化 Map
                    response.data.menuInfo.forEach((item: any) => {
                    menuMap.set(item.menuId, { ...item, children: [] });
                    });
                    // 获取节点及其所有子节点
                    const buildTree = (node: any) => {
                    if (node.menuParentId && menuMap.has(node.menuParentId)) {
                        // 添加到父节点的 children
                        const parentNode = menuMap.get(node.menuParentId);
                        parentNode.children.push(node);
                    } else {
                        // 如果没有父节点，视为根节点
                        tree.push(node);
                    }
                    // 递归处理所有子节点
                    response.data.menuInfo
                        .filter((child: any) => child.menuParentId === node.menuId)
                        .forEach((child: any) => buildTree(menuMap.get(child.menuId)));
                    };
                    // 构建树
                    response.data.menuInfo.forEach((item: any) => {
                    if (!item.menuParentId || !menuMap.has(item.menuParentId)) {
                        buildTree(menuMap.get(item.menuId));
                    }
                    });
                    interface TreeNode {
                        menuId: number;
                        menuName: string;
                        children?: TreeNode[];
                    }
                    const deleteNodeAndChildren = (menuId: number, nodes: TreeNode[]): TreeNode[] => {
                    return nodes
                        .filter((node: TreeNode) => node.menuId !== menuId) 
                        .map((node: TreeNode) => ({
                        ...node,
                        children: deleteNodeAndChildren(menuId, node.children ?? []),
                        }));
                    };
                    const updatedTree = deleteNodeAndChildren(parseInt(menuId), tree);
                    console.log(updatedTree)
                    transformToTreeData(updatedTree)
                } else {
                    message.error(`获取失败: ${response?.errMsg || '未知错误'}`)
                }
            } else {
                message.error('响应数据格式错误')
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 提交新增菜单
    const subAddMenu = async () => {
        setLoading(true)
        try {
            const response = await addMenu({
                menuName:form.getFieldValue('menuName'),
                menuType:form.getFieldValue('menuType'),
                path:form.getFieldValue('path'),
                desc:'',
                menuParentId:parentStatus,
                status:form.getFieldValue('status') === true?1:2,
                icon:form.getFieldValue('icon'),
                isCache:form.getFieldValue('isCache') === true?1:2,
                sort:parseInt(form.getFieldValue('sort')),
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('提交新增成功')
                    navigate('/setting/enterpriseManage/menuManage')
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 提交修改菜单
    const subEditMenu = async () => {
        setLoading(true)
        try {
            const response = await editMenu({
                menuName:form.getFieldValue('menuName'),
                menuType:form.getFieldValue('menuType'),
                path:form.getFieldValue('path'),
                menuId:parseInt(menuId),
                desc:'',
                menuParentId:parentStatus,
                status:form.getFieldValue('status') === true?1:2,
                icon:form.getFieldValue('icon'),
                isCache:form.getFieldValue('isCache') === true?1:2,
                sort:parseInt(form.getFieldValue('sort')),
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('提交新增成功')
                    navigate('/setting/enterpriseManage/menuManage')
                    setTimeout(() => {
                        window.location.reload()
                    }, 200);
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // tree组件渲染前配置
    const transformToTreeData = (handleData: any) => {
        const processNode = (node: any) => {
          // 当前节点数据处理
          node.title = node.menuName || '暂无数据';
          node.value = node.menuId;
          node.key = node.menuId || `unknown-${Math.random()}`;
          // 如有子节点，递归处理
          if (node.children && node.children.length > 0) {
            node.children = node.children.map((childNode: any) => processNode(childNode));
          }
          return node;
        };
        // 对所有顶级节点进行处理
        const treeData = handleData.map((item: any) => processNode(item));
        setTreeData(treeData); 
    };

    // 提交表单
    const checkSub = async () => {
        try {
            const values = await form.validateFields();
            if(state === '1'){
                subAddMenu()
            }else if(state === '2'){
                subEditMenu()
            }
        }catch(error){
            console.log(error)
            error.errorFields.map((item:any) => {
                message.error(item.errors[0])
            })
        }
    }

    // 匹配查询到的父级menuName
    const findMenuById = (menuData:any, menuId:any) => {
        for (const menu of menuData) {
          if (menu.menuId === menuId) {
            return menu;
          }
          if (menu.children && menu.children.length > 0) {
            const result = findMenuById(menu.children, menuId); // 递归子节点
            if (result) {
              return result;
            }
          }
        }
        return null; 
    };

    useEffect(() => {
        if(state == '2'){
            getMenuInfo()
        }
        getAllMenuInfo()
    }, []); 

    useEffect(() => {
        // if(treeData?.length > 0 && defaultParentId){
        //     const parentData = findMenuById(treeData,defaultParentId)
        //     form.setFieldsValue({ menuList: parentData.menuName || '暂无上级菜单数据' })
        // }
        // if(state === '2'){
            const updateFormFields = async () => {
                if (treeData?.length > 0 && defaultParentId) {
                  const parentData = await findMenuById(treeData, defaultParentId)
                //   console.log(parentData)
                  if (parentData) {
                    form.setFieldsValue({ menuList: parentData.menuName || '暂无数据' });
                  }
                }else{
                    form.setFieldsValue({ menuList: '根目录' });
                }
            };
            updateFormFields();
        // }
    }, [treeData,defaultParentId]); 

    useEffect(() => {
        form.setFieldsValue({ menuName: defaultMenuName });
        form.setFieldsValue({ menuType: defaultMenuType });
        form.setFieldsValue({ menuList: defaultMenuName });
        form.setFieldsValue({ sort: defaultSort });
        form.setFieldsValue({ path: defaultPath });
        form.setFieldsValue({ icon: defaultIcon });
        form.setFieldsValue({ status: defaultStatus === 1?true:false });
        form.setFieldsValue({ cache: defaultCache === 1?true:false });
    }, [defaultMenuName]);

    return (
        <div>
            {contextHolder}
            <Spin spinning={loading} fullscreen size='large'/>
            <div className={layout.formContent}>
                <h3>基本信息</h3>
                <div>
                    <Form form={form} className={layout.formView} labelAlign="right" labelCol={{ span: 6 }} style={{maxWidth: '455px'}}>
                        <Form.Item label="菜单名称" name="menuName" rules={[{ required: true, message: '请输入菜单名称' }]}>
                            <Input placeholder="请输入菜单名称" maxLength={50} />
                        </Form.Item>
                        <Form.Item label="菜单类型" name="menuType" rules={[{ required: true,message:'请选择菜单类型' }]}>
                            <Radio.Group onChange={onRadioChange} value={radioValue}>
                            <Radio value={1}>菜单</Radio>
                            <Radio value={2}>按钮</Radio>
                            {/* <Radio value={3}>筛选</Radio> */}
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="上级菜单" name="menuList" rules={[{ required: true,message:'请选择上级菜单' }]}>
                            <TreeSelect
                                value={value}
                                dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                                placeholder="请选择菜单"
                                allowClear
                                treeDefaultExpandAll
                                onChange={onTreeChange}
                                treeData={treeData} 
                            />
                        </Form.Item>
                        <Form.Item label="排序" name="sort" rules={[{ required: true }]}>
                            <Input type="number" placeholder="请输入菜单排序" />
                        </Form.Item>
                    </Form>
                </div>
            </div>
            <div className={layout.formContent}>
                <h3>菜单配置</h3>
                <div>
                    <div>
                        <Form form={form} className={layout.formView} labelAlign="right" labelCol={{ span: 6 }} initialValues={{ status: true,cache:true }} style={{maxWidth: '455px'}}>
                            <Form.Item label="菜单图标" name="icon" rules={[{ required: true, message: '请选择菜单图标' }]}>
                                <Input placeholder="请输入菜单图标" />
                            </Form.Item>
                            <Form.Item label="菜单路由" name="path" rules={[{ required: true, message: '请输入菜单路由' }]}>
                                <Input placeholder="请输入菜单路由" />
                            </Form.Item>
                            <Form.Item name="cache" label="菜单缓存" valuePropName="checked" extra="是否开启缓存菜单信息">
                                <Switch checkedChildren="开启" unCheckedChildren="关闭"/>
                            </Form.Item>
                            <Form.Item name="status" label="状态" valuePropName="checked" extra="此菜单可见状态" style={{marginTop:'-10px'}}>
                                <Switch checkedChildren="正常" unCheckedChildren="禁用"/>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
            </div>
            <div className={layout.buttonView}>
                <Button type="primary" onClick={checkSub}>保存</Button>
                <Button style={{marginLeft: 10}} onClick={() => {
                    navigate(-1)
                }}>返回</Button>
            </div>
        </div>
    )
}

export default menuDetail